﻿using System.Collections.Generic;
using System.Domain.Entity;
using System.Domain.IRepository;
using System.Linq;
using System.Repository.Base;
using System.Repository.DataBase.Models;
using System.Security.Cryptography;
using System.Text;
using Domain.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace System.Repository
{
    public class SysUserRepository : RepositoryDomain<SysUserEntity, Sys_User>, ISysUserRepository
    {
        public SysUserRepository(IDbContextConfig config) : base(config)
        {
        }
        /// <summary>
        /// 自动生成编号  201008251145409865
        /// </summary>
        /// <returns></returns>
        public static string CreateNo()
        {
            Random random = new Random();
            string strRandom = random.Next(1000, 10000).ToString(); //生成编号 
            string code = DateTime.Now.ToString("yyyyMMddHHmmss") + strRandom;//形如
            return code;
        }
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">加密字符</param>
        /// <param name="code">加密位数16/32</param>
        /// <returns></returns>
        public static string Md5(string str, int code = 32)
        {
            var result = "";
            using (var md5 = MD5.Create())
            {
                var temp = md5.ComputeHash(Encoding.ASCII.GetBytes(str));
                var strResult = BitConverter.ToString(temp);
                result = strResult.Replace("-", "");
            }
            string strEncrypt = "";
            switch (code)
            {
                case 8:
                    strEncrypt = result.Substring(0, 8);
                    break;
                case 16:
                    strEncrypt = result.Substring(8, 16);
                    break;
                case 32:
                    strEncrypt = result;
                    break;
            }

            return strEncrypt;
        }


        #region 为了效率重写 模型转换方法
        /// <summary>
        /// 数据库模型 转 domain 模型 重写
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public override SysUserEntity AutoCopy(SysUserEntity domain, Sys_User data)
        {
            if (data != null)
            {
                if (domain == null)
                {
                    domain = new SysUserEntity();
                }

                domain.Id = data.Id;//用户主键			   
                domain.Account = data.Account;//账户			   
                domain.RealName = data.RealName;//姓名			   
                domain.NickName = data.NickName;//呢称			   
                domain.HeadIcon = data.HeadIcon;//头像			   
                //domain.Sex = (SexEnum)((bool)data.Gender ? 1 : 0);//性别			   
                //domain.Gender = data.Gender == 1;//性别			   
                domain.Gender = data.Gender;//性别			   
                domain.Birthday = Convert.ToDateTime(data.Birthday);//生日	
                if (domain.Birthday == DateTime.MinValue)
                    domain.Birthday = null;
                domain.MobilePhone = data.MobilePhone;//手机			   
                domain.Email = data.Email;//邮箱			   
                domain.WeChat = data.WeChat;//微信			   
                //domain.SecurityLevel = data.SecurityLevel;//安全级别			   
                domain.Signature = data.Signature;//个性签名			   
                domain.OrganizeId = data.OrganizeId;//组织主键	 
                domain.DepartmentId = data.DepartmentId;//部门主键			   
                domain.PositionId = data.WorkId;//职位主键		
                domain.RoleId = data.RoleId;//权限		 
                //domain.IsAdministrator = data.IsAdministrator;//是否管理员			   
                domain.SortCode = Convert.ToInt32(data.SortCode);//排序码			   

                //domain.DeleteMark = data.DeleteMark == 1;//删除标志			   
                //domain.EnabledMark = data.EnabledMark;//有效标志			   
                domain.DeleteMark = data.DeleteMark;//删除标志			   
                domain.EnabledMark = data.EnabledMark;//有效标志
                domain.Description = data.Description;//描述			   
                domain.CreatorTime = data.CreatorTime;//创建时间			   
                domain.CreatorUserId = data.CreatorUserId;//创建用户			   
                domain.LastModifyTime = data.LastModifyTime;//最后修改时间			   
                domain.LastModifyUserId = data.LastModifyUserId;//最后修改用户			   
                domain.DeleteTime = data.DeleteTime;//删除时间			   
                domain.DeleteUserId = data.DeleteUserId;//删除用户 
                return domain;
            }
            return null;
        }
        /// <summary>
        /// domain 模型 转数据库模型 重写
        /// </summary>
        /// <param name="data"></param>
        /// <param name="domain"></param>
        /// <returns></returns>
        public override Sys_User AutoCopy(Sys_User data, SysUserEntity domain)
        {
            if (domain != null)
            {
                if (data == null)
                {
                    data = new Sys_User();
                }
                data.Id = domain.Id;//用户主键			   
                data.Account = domain.Account;//账户			   
                data.RealName = domain.RealName;//姓名			   
                data.NickName = domain.NickName;//呢称			   
                data.HeadIcon = domain.HeadIcon;//头像			   
                //data.Gender = 1 == (int)domain.Sex;//性别			   
                //data.Gender = domain.Gender ? 1 : 0;//性别			   
                data.Gender = domain.Gender;//性别			   
                if (domain.Birthday != DateTime.MinValue)
                    data.Birthday = domain.Birthday;//生日		 
                data.MobilePhone = domain.MobilePhone;//手机	 
                data.Email = domain.Email;//邮箱			   
                data.WeChat = domain.WeChat;//微信	 
                // data.SecurityLevel = domain.SecurityLevel;//安全级别			   
                data.Signature = domain.Signature;//个性签名			   
                data.OrganizeId = domain.OrganizeId;//组织主键			
                data.DepartmentId = domain.DepartmentId;//部门主键	
                data.WorkId = domain.PositionId;//职位主键			   
                data.RoleId = domain.RoleId;//角色
                //data.IsAdministrator = domain.IsAdministrator ? 1 : 0;//是否管理员			   
                data.IsAdministrator = domain.IsAdministrator;//是否管理员			   
                data.SortCode = domain.SortCode;//排序码			   
                //data.DeleteMark = (bool)domain.DeleteMark ? 1 : 0;//删除标志			   
                data.DeleteMark = domain.DeleteMark;//删除标志		
                data.EnabledMark = domain.EnabledMark;// ? 1 : 0;//有效标志			   
                data.Description = domain.Description;//描述			    

                if (domain.CreatorTime != null)
                    data.CreatorTime = domain.CreatorTime;//创建时间	
                if (domain.CreatorUserId != null)
                    data.CreatorUserId = domain.CreatorUserId;//创建用户	
                if (domain.LastModifyTime != null)
                    data.LastModifyTime = domain.LastModifyTime;//最后修改时间	
                if (domain.LastModifyUserId != null)
                    data.LastModifyUserId = domain.LastModifyUserId;//最后修改用户	
                if (domain.DeleteTime != null)
                    data.DeleteTime = domain.DeleteTime;//删除时间	
                if (domain.DeleteUserId != null)
                    data.DeleteUserId = domain.DeleteUserId;//删除用户 
                return data;

            }
            return null;



        }
        #endregion

        public override bool Update(SysUserEntity entity)
        {
            var model = GetModel(entity.Id);
            if (model == null)
                return false; 
            AutoCopy(model, entity);
            return Update(model); 
        }

        public override bool Insert(SysUserEntity entity)
        {
            // 事务例子
            //用户登陆信息
            Sys_UserLogOn userLogOnEntity = new Sys_UserLogOn
            {
                Id = entity.Id,
                UserId = entity.Id,
                UserSecretkey = Md5(CreateNo(), 16).ToLower(),
                MultiUserLogin = false,
                LogOnCount = 0,
                UserOnLine = false
            };
            //userLogOnEntity.UserPassword = Md5.md5(DesEncrypt.Encrypt(Md5.md5(entity.UserPassword, 32).ToLower(), userLogOnEntity.UserSecretkey).ToLower(), 32).ToLower();
            userLogOnEntity.UserPassword = Md5(Md5(entity.UserPassword).ToLower() + userLogOnEntity.UserSecretkey).ToLower();
            Sys_User model = AutoCopy(null, entity);


            var temp = Transaction(() =>
            {
                Dbcontext.Entry(model).State = EntityState.Added;
                Dbcontext.Entry(userLogOnEntity).State = EntityState.Added;
                return Dbcontext.SaveChanges() > 0;

            });
            return temp;

        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool RevisePassword(string keyValue, string password)
        {
            Sys_UserLogOn model = Dbcontext.Set<Sys_UserLogOn>().Where(t => t.Id == keyValue).ToList().FirstOrDefault();
            if (model == null)
                return false;
            Dbcontext.Set<Sys_UserLogOn>().Attach(model);
            // model.UserPassword = Md5.md5(DesEncrypt.Encrypt(Md5.md5(password, 32).ToLower(), model.UserSecretkey).ToLower(), 32).ToLower();
            model.UserPassword = Md5(Md5(password).ToLower() + model.UserSecretkey).ToLower();
            model.ChangePasswordDate = DateTime.Now;
            Dbcontext.Entry(model).State = EntityState.Modified;

            return Dbcontext.SaveChanges() > 0;
        }


        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public SysUserEntity Login(string username, string password)
        {

            //var expression = ExtLinq.True<Sys_User>().And(t => t.Account == username);
            var userModel = GetModel(t => t.Account == username);

            //  return AutoCopy(null, userModel);
            if (userModel != null)
            {
                Sys_UserLogOn model = Dbcontext.Set<Sys_UserLogOn>().Where(t => t.Id == userModel.Id).ToList().FirstOrDefault();
                if (model != null)
                {
                    if (model.UserPassword.Equals(Md5(Md5(password).ToLower() + model.UserSecretkey).ToLower()))
                    //if (model.UserPassword.Equals(Md5.md5(DesEncrypt.Encrypt(Md5.md5(password, 32).ToLower(), model.UserSecretkey).ToLower(), 32).ToLower()))
                    {
                        //var entity 
                        model.LastVisitTime = DateTime.Now;
                        if (model.LogOnCount == null)
                            model.LogOnCount = 0;
                        model.LogOnCount++;
                        Dbcontext.Entry(model).State = EntityState.Modified;
                        if (Dbcontext.SaveChanges() > 0)
                        {
                            return AutoCopy(null, userModel);
                        }
                        //修改登陆状态 失败
                    }
                    //密码错误

                }
                //用户表 和密码表关联错误
                return AutoCopy(null, userModel);
            }
            //用户名错误


            return null;
        }

        public List<SysUserEntity> GetList(Pagination pagination, string companyId, string departmentId, string positionId, string userId)
        {
            var expression = ExtLinq.True<Sys_User>();
            //  expression = expression.And(t => t.CreatorTime >= start).And(t => t.CreatorTime <= end);
            if (!string.IsNullOrEmpty(userId))
                expression = expression.And(t => t.Id == userId);
            else
            {
                if (!string.IsNullOrEmpty(companyId))
                    expression = expression.And(t => t.OrganizeId == companyId);
                if (!string.IsNullOrEmpty(departmentId))
                    expression = expression.And(t => t.DepartmentId == departmentId);
                if (!string.IsNullOrEmpty(positionId))
                    expression = expression.And(t => t.WorkId == positionId);

            }
            return GetList(expression, pagination);
        }


    }

}
